package com.example.mactchoperator;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class BluetoothMockClient {

    private final String host;
    private final int port;

    private final WriterTCP writerTCP;

    public BluetoothMockClient(String host, int port) {
        this.host = host;
        this.port = port;
        writerTCP = new WriterTCP(host, port);
        Thread t = new Thread(writerTCP);
        t.start();
    }
    
    public boolean send(String message){
        return writerTCP.send(message);
    }
    
    public boolean isConnected(){
        return writerTCP.isConnected();
    }

    private class WriterTCP implements Runnable {

        private final String host;
        private final int port;

        private Socket clientSocket = null;
        private DataOutputStream output = null;

        public WriterTCP(String host, int port) {
            this.host = host;
            this.port = port;
        }

        public boolean isConnected(){
            if(clientSocket == null){
                return false;
            }
            System.out.println("coucou");
            return clientSocket.isConnected();
        }
        
        @Override
        public void run() {
            while (true) {
                while (clientSocket == null || !clientSocket.isConnected()) {
                    try {
                        clientSocket = new Socket(host, port);
                        output = new DataOutputStream(clientSocket.getOutputStream());
                    } catch (IOException ex) {
                        clientSocket = null;
                        output = null;
                        Logger.getLogger(BluetoothMockClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                send("coucouc");
            }
        }
        
        public boolean send(String message){
            if(output == null || clientSocket == null){
                return false;
            }
            message +="\n";
            try {
                output.write(message.getBytes());
            } catch (IOException ex) {
                clientSocket = null;
                output = null;
                Logger.getLogger(BluetoothMockClient.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
            return true;
        }

    }
    
    public static void  main(String[] args){
    	BluetoothMockClient c = new BluetoothMockClient("localhost", 6789);
        System.out.println(c.isConnected());
        System.out.println(c.send("un message"));
    }

}
